# coding=utf-8
from openpyxl import load_workbook
import sys
import json
import copy

const_name_col = 2
const_value_col = 3

id_val_dict = {}
func_param_dict = {}

#解析一个功能的返回数据
def parse_one_function(sheet):
    funcno = ""
    func_param_name = []
    param_begin_index = 0
    for row_indx in range(2, sheet.max_row):
        index_name = sheet.cell(row_indx, const_name_col).value   
        
        if index_name == "功能号":
            param_begin_index = 0

            funcno = str(sheet.cell(row_indx, const_value_col).value)
            if len(funcno) == 0:
                continue

            if len(func_param_name) > 0:
                func_param_dict.update({funcno: copy.deepcopy(func_param_name)})

        elif index_name == "输出参数":
            func_param_name.clear()
            param_begin_index = row_indx
            curr_id = sheet.cell(row_indx, const_value_col).value
            func_param_name.append(id_val_dict[curr_id])
        else:
            curr_id = sheet.cell(row_indx, const_value_col).value
            if param_begin_index != 0 and curr_id != None:
                curr_val = id_val_dict.get(curr_id)
                if(curr_val == None):
                    curr_val = sheet.cell(row_indx, 4).value

                func_param_name.append(curr_val)


def parse_id_def(sheet):
    for row_indx in range(3, sheet.max_row):
        fid_def = sheet.cell(row_indx, 2).value
        fid_val = int(sheet.cell(row_indx, 3).value)
        id_val_dict[fid_def] = fid_val


excel_file_name_dict = {"stock" : "顶点ABOSS标准第三方接口.xlsm", "option" : "个股期权第三方接口.xlsm"}
json_file_name_dict = {"stock" : "dd_stock_id_val.json", "option" : "dd_option_id_val.json"}


def parse_excel_to_json(type:str):
    func_param_dict.clear()
    id_val_dict.clear()

    workbook = load_workbook(excel_file_name_dict[type])

    id_sheet = workbook["基本字段定义"]
    parse_id_def(id_sheet)
   
    info_sheet = workbook["接口信息"]
    parse_one_function(info_sheet)

    with open(json_file_name_dict[type], "w") as file:
        json.dump(func_param_dict, file)


if __name__ == '__main__':

    #execl_file_name = "./顶点ABOSS标准第三方接口.xlsm"
    #json_file_name = "dd_stock_id_val.json"
    #execl_file_name = "./个股期权第三方接口.xlsm"
    #json_file_name = "dd_option_id_val.json"

    parse_excel_to_json("stock")
    parse_excel_to_json("option")
    
